/*global L, mnccolors, mnclinks, InfoControl*/
/*jslint browser: true*/
var map, markers, circle, httpRequest = new XMLHttpRequest(), addedPoints = [], mapInfo = new InfoControl({position: 'bottomright', content: ''});

function displayCircle(e) {
    'use strict';
    if (circle) {
        map.removeLayer(circle);
    }
    circle = L.circle(e.target.getLatLng(), e.target.feature.properties.range);
    circle.addTo(map);
}

function showPopup(feature, layer) {
    'use strict';
    var color,
        popupContent = 
            '<b>MCC</b>: ' + feature.properties.mcc +
            '<br/><b>MNC</b>: ' + feature.properties.net +
            '<br/><b>LAC</b>: ' + feature.properties.area +
            '<br/><b>CID</b>: ' + feature.properties.cell +
            '<br/><b>Radio Type</b>: ' + (feature.properties.radio || 'Unknown') +
            '</br></br><b>Latitude</b>: ' + feature.geometry.coordinates[1] +
            '</br><b>Longitude</b>: ' + feature.geometry.coordinates[0] +
            '</br><b>Range</b>: ' + feature.properties.range + ' m' +
            '<br/><br/><i>' + feature.properties.samples + '</i> measurements' +
            '</br><b>Created</b>: ' + new Date(feature.properties.created * 1000).toISOString() +
            '</br><b>Updated</b>: ' + new Date(feature.properties.updated * 1000).toISOString();
        color = '#000000';
    layer.bindPopup(
        popupContent,
        { autoPan: false }
    );
    var radioIcon = feature.properties.radio.substr(0, 1).toLowerCase();
    var iconColor;
    if (radioIcon == "g") {
        iconColor = 'E90003';
    } else if (radioIcon == "c") {
        iconColor = 'ED1B24';
    } else if (radioIcon == "u") {
        iconColor = 'FF6600';
    } else if (radioIcon == "l") {
        iconColor = '00ACD5';
    } else {
        iconColor = '6E6F72';
    } 
    
    layer.options.icon = L.icon({
        iconUrl: "https://api.tiles.mapbox.com/v3/marker/pin-m-" + radioIcon + "+" + iconColor + ".png"
    });
    layer.on('click', displayCircle);
}

function addNewMarkers(feature) {
    'use strict';
    if (addedPoints.indexOf(feature.geometry.coordinates[0] + ',' + feature.geometry.coordinates[1]) >= 0) {
        return false;
    }
    addedPoints.push(feature.geometry.coordinates[0] + ',' + feature.geometry.coordinates[1]);
    return true;
}

function showMarkers(e) {
    'use strict';
    if (e.target.readyState === 4 && e.target.status === 200) {
        var cells = JSON.parse(e.target.response);
        markers.addLayer(
            L.geoJson(
                cells,
                {
                    onEachFeature: showPopup,
                    filter: addNewMarkers
                }
            )
        );
    }
}

function getMarkers() {
    'use strict';
    //Don't fetch cells if zoom level is too high
    var zoomLev = map.getZoom();
    if (zoomLev < 16){
        return;
    }
        
    httpRequest.onreadystatechange = showMarkers;
    httpRequest.open('GET', 'ajax/getCells.php?bbox=' + map.getBounds().toBBoxString(), true);
    httpRequest.send(null);
}

function goToCell(e) {
    'use strict';
    if (e.target.readyState === 4 && e.target.status === 200) {
        var cell = JSON.parse(e.target.response);
        if (cell) {
            map.setView(cell, 18);
        }
    }
}

var SearchCellControl = L.Control.extend(
    {
        initialize: function (options) {
            'use strict';
            L.Util.setOptions(this, options);
        },
        searchCell: function () {
            'use strict';
            var ajax = new XMLHttpRequest();
            ajax.onreadystatechange = goToCell;
            ajax.open('GET', 'ajax/searchCell.php?mcc=' + document.getElementById('mcc').value + '&mnc=' + document.getElementById('mnc').value + '&lac=' + document.getElementById('lac').value + '&cell_id=' + document.getElementById('cell_id').value);
            ajax.send(null);
        },
        onAdd: function () {
            'use strict';
            var container = L.DomUtil.create('div', 'search-cell-control'), fields = ['MCC', 'MNC', 'LAC', 'Cell ID'], i, id, field, label, input, br, submitBtn = L.DomUtil.create('button', '');
            container.insertAdjacentHTML('beforeend', '<div style="margin-bottom:5px"><b>Search Cell Towers</b></div>');
            for (i = 0; i < fields.length; i += 1) {
                id = fields[i].toLowerCase().replace(' ', '_');
                field = L.DomUtil.create('div', 'cellsearch-line');
                label = L.DomUtil.create('label', 'cellsearch-label');
                label.textContent = fields[i];
                label.setAttribute('for', id);
                field.appendChild(label);
                input = L.DomUtil.create('input', 'cellsearch-input');
                input.setAttribute('type', 'number');
                input.setAttribute('id', id);
                field.appendChild(input);
                br = L.DomUtil.create('br', '');
                field.appendChild(br);
                container.appendChild(field);
            }
            submitBtn.textContent = 'Search';
            submitBtn.addEventListener('click', this.searchCell, false);
            container.appendChild(submitBtn);
            L.DomEvent.disableClickPropagation(container);
            return container;
        }
    }
);

function init() {
    'use strict';
    var key = 'pk.4bc69031131258dca5fe22190cbb9a40';
    var streets = L.tileLayer.Unwired({key: key, scheme: "streets"});
    map = L.map('map', {
        center: [37.77889,-122.41942], //map loads with this location as center
        zoom: 16,
        maxZoom: 18,
        minZoom: 2,
        layers: [streets], // Show 'streets' by default
        scrollWheelZoom:false
    });
    map.zoomControl.setPosition('topright');
    map.addControl(new L.Control.Fullscreen({
        position: "topright"
    }));

    L.control.locate(
        {
            position: 'bottomright'
        }
    ).addTo(map);

    var coverage = L.tileLayer(
        "https://opencellid.org/images/maps/opencellid/{z}/{x}/{y}.png?v=",
        {
            maxNativeZoom: 10,
            maxZoom: 15,
        }
    ), legend = L.control({position: 'bottomright'});
    markers = new L.MarkerClusterGroup({ disableClusteringAtZoom: 18 }).addTo(map);
    coverage.addTo(map);
    L.control.layers({ 'Streets': streets }, { 'Coverage': coverage, 'Cells': markers }).addTo(map);
    map.on('moveend', getMarkers);
    getMarkers();
    // map.addControl(
    //     new L.Control.Geocoder(
    //         {
    //             collapsed: false,
    //             geocoder: new L.Control.Geocoder.Nominatim({ serviceUrl: 'https://nominatim.openstreetmap.org/' }),
    //             position: 'topleft'
    //         }
    //     )
    // );
    map.addControl(L.control.scale());
    map.addControl(new L.Control.Permalink({ useLocation: true, text: null }));

    L.control.geocoder('pk.3bc69031431258dca', {
        // placeholder: 'Search nearby',
        url: "https://pelias.locationiq.org/v1",
        expanded: true,
        panToPoint: true,
        focus: false,
        attribution: "",
        position: "topleft"
    }).addTo(map);

    map.addControl(new SearchCellControl({position: 'topleft'}));
    map.addControl(mapInfo);

    //getTimestamp();
    legend.onAdd = function () {
        var div = L.DomUtil.create('div', 'info legend leaflet-control-attribution'),
            radioTypes = [
                ['G', 'GSM'],
                ['C', 'CDMA'],
                ['U', 'UMTS'],
                ['L', 'LTE']
            ];
        div.innerHTML += '<span style="line-height: 10px;"><small>Reds denote fewer cells, <br/>whites are denser areas.<br /></span>';
        div.innerHTML += '<img src="/images/gradient-legend.png"><br />';
        radioTypes.forEach(
            function (radioType) {
                div.innerHTML += '<b>' + radioType[0] + '</b>: ' + radioType[1] + '<br />';
            }
        );
        return div;
    };

    legend.addTo(map);
}

window.addEventListener('load', init, false);
